<template>
  <div class="clearfix">
    <div v-for="(item, index) in fileList" :key="index" class="Uploading_img_warps">
      <div class="Uploading_img_warp">
        <div class="Uploading_imgs">
          <div class="masking" v-if="item.imgUrl && limit !== 0">
            <div class="maskings">
              <a-icon type="eye" v-if="item.type === 'img'" class="icon" style="color: #fdfdfd" @click="handlePreview(item)" />
              <a-icon style="color: #fdfdfd" type="eye-invisible" class="icon" v-if="item.type === 'file'" />

              <a-icon style="color: #fdfdfd" type="delete" class="icon" @click="ondelete(index)" />
            </div>
          </div>
          <img :src="item.imgUrl" alt="" class="Uploading_img" v-if="item.type === 'img' && item.imgUrl" />
          <div>
            <div class="Uploading_loading" v-if="!item.imgUrl">
              <a-icon slot="indicator" type="loading" style="font-size: 24px" spin />
            </div>
          </div>

          <a-icon type="file-text" class="Uploading_file" v-if="item.type === 'file' && item.imgUrl" />
        </div>
      </div>
      <p style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis">{{ item.name }}</p>
    </div>
    <a-upload
      class="uploading"
      action="/file/api/v1/site/upload/inline"
      list-type="picture-card"
      :file-list="fileList"
      :multiple="multiple"
      name="files"
      accept=".doc, .docx, .xls, .xlsx, .pdf, .zip, .rar, .jpg, .jpeg, .png"
      :showUploadList="false"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < limit">
        <slot name="antUpload">
          <a-icon type="plus" />
          <div class="ant-upload-text">上传</div>
        </slot>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  props: {
    srcData: {
      type: String,
      default: ""
    },
    multiple: {
      // 选择时是否可以选择多个
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  watch: {
    srcData: {
      handler: function (val, oldVal) {
        this.fileList = [];
        if (val && val !== "") {
          const srcData = JSON.parse(JSON.stringify(val));
          srcData.split(",").forEach((element, index) => {
            this.fileList.push({
              uid: index,
              name: element.split("/").slice(-1)[0],
              status: "done",
              type: this.imgTypes.includes(element.split("/").slice(-1)[0].split(".").splice(-1)[0]) ? "img" : "file",
              src: element,
              imgUrl: `${element}?token=${this.$store.state.auth.token}`,
              url: `${element}?token=${this.$store.state.auth.token}`
            });
          });
        }
      },
      deep: true
    }
  },
  created() {
    if (this.srcData && this.srcData !== "") {
      const srcData = JSON.parse(JSON.stringify(this.srcData));
      srcData.split(",").forEach((element, index) => {
        this.fileList.push({
          uid: index,
          name: element.split("/").slice(-1)[0],
          status: "done",
          type: this.imgTypes.includes(element.split("/").slice(-1)[0].split(".").splice(-1)[0]) ? "img" : "file",
          src: element,
          imgUrl: `${element}?token=${this.$store.state.auth.token}`,
          url: `${element}?token=${this.$store.state.auth.token}`
        });
      });
    }
  },
  data() {
    return {
      previewVisible: false,
      previewImage: "",
      fileList: [],
      imgTypes: [
        "bmp",
        "jpg",
        "png",
        "tif",
        "gif",
        "pcx",
        "tga",
        "exif",
        "fpx",
        "svg",
        "psd",
        "cdr",
        "pcd",
        "dxf",
        "ufo",
        "eps",
        "ai",
        "raw",
        "WMF",
        "webp",
        "jpeg"
      ]
    };
  },
  methods: {
    ondelete(index) {
      var that = this;
      this.$confirm({
        title: "正在删除",
        content: "删除后将无法恢复，确认删除该附件吗？",
        onOk() {
          that.fileList.splice(index, 1);
          const fileList = JSON.parse(JSON.stringify(that.fileList));
          const fileListString = [];
          fileList.forEach((element, index) => {
            fileListString.push(element.src);
          });
          that.$emit("update:srcData", fileListString.join(","));
          that.$emit("change", fileListString.join(","));
        }
      });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handlePreviews(file) {
      window.open(file.imgUrl);
    },
    handleChange({ file, fileList }) {
      if (file.status === "done" || file.status === "removed") {
        const fileListString = [];
        fileList.forEach((element, index) => {
          if (element.response) {
            element.src = element.response.data[0];
            element.imgUrl = `${element.response.data[0]}?token=${this.$store.state.auth.token}`;
            element.type = this.imgTypes.includes(element.name.split(".").splice(-1)[0]) ? "img" : "file";
            fileListString.push(element.src);
            this.$set(fileList, index, element);
          } else {
            fileListString.push(element.src);
          }
        });
        this.$emit("update:srcData", fileListString.join(","));
        this.$emit("change", fileListString.join(","));
      }

      this.fileList = fileList;
    }
  }
};
</script>
<style lang="scss" scoped>
.uploading {
  width: 104px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.clearfix {
  display: flex;
  flex-wrap: wrap;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.Uploading_img_warp {
  width: 104px;
  height: 104px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.Uploading_imgs {
  position: relative;
  width: 90px;
  height: 90px;
  overflow: hidden;
}
.Uploading_img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.masking {
  background-color: rgba(0, 0, 0, 0.5);
  display: none;
  width: 90px;
  height: 90px;
  position: absolute;
  left: 0;
  right: 0;
}
.maskings {
  width: 100%;
  height: 90px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.Uploading_imgs:hover .masking {
  display: block;
}
.Uploading_file {
  display: inline-block;
  font-size: 90px;
  line-height: 90px;
}
.icon {
  cursor: pointer;
  color: #fff;
}
.Uploading_img_warps {
  width: 114px;
  margin: 0 8px 8px 0;
}
.Uploading_loading {
  width: 100%;
  height: 90px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
